package com.koron.css2.newProjectCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.newProjectCenter.bean.PjDelay;
import com.koron.css2.newProjectCenter.bean.PjInfoBean;
import com.koron.css2.newProjectCenter.mapper.PjDelayMapper;
import com.koron.css2.newProjectCenter.mapper.PjInfoMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.Date;

public class PjDelayInsert implements ServerInterface {
    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            PjDelay pjDelay = JsonUtils.objectToPojo(req.getData(),PjDelay.class);
            PjDelayMapper pjDelayMapper = factory.getMapper(PjDelayMapper.class);
            PjInfoMapper pjInfoMapper = factory.getMapper(PjInfoMapper.class);

            // 1. 查出对应的工程报装
            PjInfoBean pjInfoBean = pjInfoMapper.selectByBillNo(pjDelay.getPjBillNo());
            // 2. 判断是否正在终止
            Integer terminationFlag = pjInfoBean.getTerminationFlag();
            if (terminationFlag != null && terminationFlag == 1) {
                return MessageBean.create(Constant.MESSAGE_INT_FAIL,"当前节点正在终止，无法延期",null);
            }
            // 3. 判断是否正在延期
            Integer delayFlag = pjInfoBean.getDelayFlag();
            if (delayFlag != null && delayFlag == 1) {
                return MessageBean.create(Constant.MESSAGE_INT_FAIL,"当前节点正在延期，无法再次延期",null);
            }
            // 4. id,createTime,createAccount,createName,tenantId
            pjDelay.setCreateInfo(userInfo);
            // 5. billNo,billDate
            pjDelay.setBillNo(Tools.getBillNo(factory,"pj_delay"));
            pjDelay.setBillDate(new Date());
            pjDelayMapper.insert(pjDelay);
            // 6. 修复工程表延期字段已延期
            pjInfoBean.setDelayFlag(1);
            pjInfoMapper.update(pjInfoBean);
            // 7. 返回结果
            MessageBean<String> messageBean = MessageBean.create(Constant.MESSAGE_INT_SUCCESS,"延期新增成功",String.class);
            messageBean.setData(pjDelay.getId());
            return messageBean;
        } catch (Exception e) {
            logger.error("延期新增失败",e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL,"延期新增失败",null);
        }
    }
}
